package data;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.DomainModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

public class DomainData {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "";
	
	public DomainData() {
		try {
			ObjectifyService.register(DomainModel.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public DomainModel get(String domainName) {
		DomainModel domain = new DomainModel();
		
		if (cache != null && cache.containsKey(prefix + domainName)) {
			domain = (DomainModel) cache.get(prefix + domainName);
		} else {
			try {
				domain = ofy.get(new Key<DomainModel>(DomainModel.class, domainName));
				cache.put(prefix + domainName, domain);
			} catch (Exception e) {
				domain = null;
			}
		}
		return domain;
	}
	
	public void insert(DomainModel domain) {
		if (cache != null) {
			cache.put(prefix + domain.getDomain(), domain);
		}
		ofy.put(domain);
	}
	
	public void delete(DomainModel domain) {
		if (cache != null && cache.containsKey(prefix + domain.getDomain())) {
			cache.remove(prefix + domain.getDomain());
		}
		ofy.delete(domain);
	}

}
